package com.sgb.link.view.adapter;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;
import androidx.annotation.IdRes;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Description:
 * Author zhengkewen
 * Time 2017/12/13
 */
public class ItemViewHolder extends RecyclerView.ViewHolder {

    private ViewDataBinding mBinding;
    private View item;
    private final SparseArray<View> views;
    private int index_position = -1;

    public int getIndex_position() {
        return index_position;
    }

    public void setIndex_position(int index_position) {
        this.index_position = index_position;
    }

    public ItemViewHolder(View v) {
        super(v);
        this.item = v;
        this.views = new SparseArray<>();
        mBinding = DataBindingUtil.bind(v);
    }

    public static ItemViewHolder get(Context context, ViewGroup viewGroup, int layoutId) {
        View itemView = LayoutInflater.from(context).inflate(layoutId, viewGroup, false);
        return new ItemViewHolder(itemView);
    }

    public View getItem() {
        return item;
    }

    public ItemViewHolder setBinding(int variableId, Object object) {
        mBinding.setVariable(variableId, object);
        mBinding.executePendingBindings();
        return this;
    }

    public ViewDataBinding getmBinding() {
        return mBinding;
    }

    @SuppressWarnings("unchecked")
    public <T extends View> T getView(@IdRes int viewId) {
        View view = views.get(viewId);
        if (view == null) {
            view = itemView.findViewById(viewId);
            views.put(viewId, view);
        }
        return (T) view;
    }

    public ItemViewHolder setText(@IdRes int viewId, CharSequence value) {
        TextView view = getView(viewId);
        view.setText(value);
        return this;
    }

    public ItemViewHolder setImageResource(@IdRes int viewId, @DrawableRes int imageResId) {
        ImageView view = getView(viewId);
        view.setImageResource(imageResId);
        return this;
    }

    public ItemViewHolder setBackgroundColor(@IdRes int viewId, @ColorInt int color) {
        View view = getView(viewId);
        view.setBackgroundColor(color);
        return this;
    }

    public ItemViewHolder setVisible(@IdRes int viewId, boolean visible) {
        View view = getView(viewId);
        view.setVisibility(visible ? View.VISIBLE : View.GONE);
        return this;
    }

}
